import {
  DragElement,
  ExtensionCategory,
  register,
  type GraphData,
} from '@antv/g6'
import { CustomRect } from './nodes/custom-rect'
import type { ETLNodeItem } from './type'
import { defaultStyles } from './defaultStyle'

/**
 * 注册图表能力（节点，边，行为，事件等）
 */
export function registerBase() {
  register(ExtensionCategory.NODE, 'custom-rect', CustomRect)
  register(ExtensionCategory.BEHAVIOR, 'drag-node', DragElement)
}

export function generateData(list: ETLNodeItem[]): GraphData {
  const data: GraphData = { nodes: [], edges: [] }
  list.forEach(el => {
    const { id, type, label, x, y, nextId, prevIds } = el
    data.nodes?.push({
      id,
      type,
      data: { id, type, label, x, y, nextId, prevIds },
      style: {
        labelText: label,
        x,
        y,
        ports: [
          {
            key: 'left',
            placement: [0, 0.5],
            ...defaultStyles.portStyle,
          },
          {
            key: 'right',
            placement: [1, 0.5],
            ...defaultStyles.portStyle,
          },
        ],
        iconText: el.icon,
        iconFill: '#000',
      },
    })
    if (prevIds?.length) {
      prevIds.forEach(prevId => {
        data.edges?.push({ id: `${prevId}-${id}`, source: prevId, target: id })
      })
    }
  })
  return data
}
